//
//  EcgReportViewController.m
//  Ikinloop-demo
//
//  Created by Li Shen on 2021/4/19.
//  Copyright © 2021 lyh. All rights reserved.
//

#import "EcgReportViewController.h"
#import "IKEcgReportChartView.h"

#import "CellBean.h"
#import "ResultBean.h"
#import "ResultTextBean.h"
#import "ResultInfoTitleBean.h"
#import "ResultContentBean.h"
#import "HeartRateProgressBean.h"
#import "BreatheRateProgressBean.h"
#import "TableIntervalBean.h"
#import "ResultProgressBean.h"

#import "ResultInfoTitleCell.h"
#import "ResultContentCell.h"
#import "ResultTextCell.h"
#import "ResultProgressCell.h"
#import "TableIntervalCell.h"
#import "HeartRateProgressCell.h"
#import "ResultCell.h"
#import "BreatheRateProgressCell.h"
#import <IKLibrary/IKLibrary.h>


@interface EcgReportViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) IKEcgReportChartView *reportChartView;
@property (nonatomic, strong) UIView *lineChartRootView;

@property (nonatomic,strong) NSArray<NSArray<CellBean*>*>* cellBeans;
@property (nonatomic,assign) CGRect ecgFrameP;// 心电图竖直状态frame
@property (nonatomic,assign) CGRect ecgFrameL;// 心电图水平状态frame
@property (nonatomic,copy) NSString *timestamp;

@property (nonatomic, strong) NSDictionary *smartResultDic;

@end

@implementation EcgReportViewController
{
    NSInteger ecgViewHeight;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"检测结果";
    self.view.backgroundColor = [UIColor whiteColor];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
//    self.navigationController.navigationBar.translucent = NO;
    [self initTableView];
    [self localECGdata];
    [self loadECGData];
}

- (void)initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    ecgViewHeight = [IKPublicUtil mm2pt:40.2];
    self.ecgFrameP = CGRectMake(0, 0, KScreenW, ecgViewHeight);
    self.ecgFrameL = CGRectMake(0, (KScreenW - ecgViewHeight) / 2, KScreenH, ecgViewHeight);
    
    self.reportChartView = [[IKEcgReportChartView alloc] init];
    [self.reportChartView IKEcgDrawinit];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:self.ecgFrameP];
    [self.tableView.tableHeaderView addSubview:self.reportChartView];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenW,50)];
    [self.reportChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.tableView.tableHeaderView);
    }];
    [self.view addSubview:self.tableView];
    
    
    self.lineChartRootView = [[UIView alloc] init];
    self.lineChartRootView.hidden = YES;
   
    self.lineChartRootView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.lineChartRootView];
    
    [self.lineChartRootView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
}

- (void)setEcgSmartResult:(NSString *)ecgSmartResult{
    _ecgSmartResult = ecgSmartResult;
    NSData *jsonData = [ecgSmartResult dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err){
        NSLog(@"json解析失败：%@",err);
        return;
    }
    self.smartResultDic = dic;
}

- (void)setTarFilePath:(NSString *)tarFilePath{
    _tarFilePath = tarFilePath;
}

-(NSString *)getSuggestStr:(NSArray*)ecgsymps
{
    NSString *str = @"";
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSDictionary *symp in ecgsymps) {
        [array addObject:[@"      " stringByAppendingString:symp[@"suggestion"]]];
    }
    str = [array componentsJoinedByString:@"\n"];
    return str;
}

#pragma mark - 加载页面图标数据
- (void)loadECGData{
    if([IKPublicUtil isEmpty:self.tarFilePath] || ![self.tarFilePath.pathExtension isEqualToString:@"tar"]){
        NSLog(@"传入的tar包路径不对");
        return;
    }
    NSString *ecgFilePath = [self.tarFilePath substringWithRange:NSMakeRange(0, self.tarFilePath.length-4)];
    [self.reportChartView setEcgTarFilePath:ecgFilePath];
}

- (NSString *)getResultStr:(NSArray *)ecgsymps{
    NSString *str = @"";
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSDictionary *symp in ecgsymps) {
        [array addObject:symp[@"name"]];
    }
    str = [array componentsJoinedByString:@"/"];
    return str;
}

#pragma mark - 加载页面智能分析界面
- (void)localECGdata{
    NSMutableArray *arrays = [NSMutableArray  array];
    
    NSDictionary *ecgVal = self.smartResultDic[@"ecgval"];
    NSArray *ecgsymps = self.smartResultDic[@"ecgsymps"];
    BOOL suspectedflag = [ecgVal[@"suspectedflag"] boolValue];
    NSString *breath = ecgVal[@"breath"];
    NSString *hrmean = ecgVal[@"hrmean"];
    NSString *pressure = ecgVal[@"pressure"];
    //    NSString *heartage = ecgVal[@"heartage"];
    //    NSString *hrmax = ecgVal[@"hrmax"];
    //    NSString *hrmin = ecgVal[@"hrmin"];
    //    NSString *hrv = ecgVal[@"hrv"];
    //    NSString *pbcnt = ecgVal[@"pbcnt"];
    
    NSMutableArray<CellBean *> *beans = [NSMutableArray array];
    {
        ResultBean *resultBean = [[ResultBean alloc] init];
        resultBean.resultType = suspectedflag ? ResultTypeAlert :ResultTypeNormal;
        resultBean.resultText =resultBean.resultType == ResultTypeNormal ? @"" :[self getResultStr:ecgsymps] ;
        [beans addObject:resultBean];
    }
    {
        ResultInfoTitleBean *titleBean = [[ResultInfoTitleBean alloc] init];
        titleBean.titleImageName = @"ecg_img_xinlv";
        titleBean.title = INTERNATIONAL(@"string_hear_rate_status");
        [beans addObject:titleBean];
        //平均心率
        ResultContentBean *avgheartBean = [[ResultContentBean alloc] init];
        NSInteger avgHr  =  hrmean.integerValue;
        avgheartBean.problem = avgHr>100 || avgHr < 60 ? YES : NO;
        avgheartBean.text = [NSString stringWithFormat:@"%@ %@%@",INTERNATIONAL(@"string_average_describ") ,hrmean , INTERNATIONAL(@"string_times_min")];
        avgheartBean.descTitle = INTERNATIONAL(@"string_average_heart_title");
        NSString *formate = @"%@\n%@";
        NSString *avgHRDesc = INTERNATIONAL(@"string_average_heart");
        NSString *infoDesc = @"";
        if(avgHr < 60){ // 心动过缓
            infoDesc = INTERNATIONAL(@"heart_rate_low");
        } else if(avgHr <= 100) { // 正常60~100
            infoDesc = @"";
        }  else { // 心动过速
            infoDesc = INTERNATIONAL(@"heart_rate_little_hight");
        }
        avgheartBean.desc = [NSString stringWithFormat:formate,avgHRDesc,infoDesc];
        [beans addObject:avgheartBean];
        
        HeartRateProgressBean *heartRateProgressBean = [[HeartRateProgressBean alloc] init];
        heartRateProgressBean.heartRate = hrmean;
        [beans addObject:heartRateProgressBean];
        
        //呼吸率
        ResultContentBean *breatheBean = [[ResultContentBean alloc] init];
        breatheBean.text = [IKPublicUtil isEmpty:breath] || [@"0" isEqualToString:breath] ? [NSString stringWithFormat:@"%@%d", INTERNATIONAL(@"string_huxi"), 0] : [NSString stringWithFormat:@"%@%@%@", INTERNATIONAL(@"string_huxi"), breath, INTERNATIONAL(@"string_times_min")];
        
        NSInteger breathReat  = breath.integerValue;
        breatheBean.problem = (breathReat >= 24 || breathReat  < 12) ? YES : NO ;
        breatheBean.desc = INTERNATIONAL(@"string_respiratory_frequency");
        breatheBean.descTitle = INTERNATIONAL(@"string_respiratory_frequency_title");
        [beans addObject:breatheBean];
        
        BreatheRateProgressBean* breatheRateProgressBean = [[BreatheRateProgressBean alloc] init];
        breatheRateProgressBean.breatheRate = breath;
        [beans addObject:breatheRateProgressBean];
                
        [arrays addObject:beans];
    }
    //间隔
    {
        beans = nil;
        beans = [[NSMutableArray alloc] init];
        TableIntervalBean * bean = [[TableIntervalBean alloc] init];
        [beans addObject:bean];
        
        [arrays addObject:beans];
    }
    
    //心理
    {
        beans = nil;
        beans = [[NSMutableArray alloc] init];
        ResultInfoTitleBean *titleBean = [[ResultInfoTitleBean alloc] init];
        titleBean.titleImageName = @"ecg_img_xinli";
        titleBean.title = INTERNATIONAL(@"string_heart_state");
        [beans addObject:titleBean];
        // 压力指数
        ResultProgressBean *pressureBean = [[ResultProgressBean alloc] init];
        NSInteger preIndex = pressure.integerValue;
        pressureBean.progress = preIndex;
        pressureBean.progressType = ResultProgressType1;
        if (preIndex >66) {
            pressureBean.problem = YES;
        }else{
            pressureBean.problem = NO;
        }
        pressureBean.text = INTERNATIONAL(@"string_mentality_title");
        pressureBean.descTitle = INTERNATIONAL(@"string_mentality_title");
        pressureBean.desc = INTERNATIONAL(@"string_mentality");
        [beans addObject:pressureBean];
        [arrays addObject:beans];
    }
    //间隔
    {
        beans = nil;
        beans = [[NSMutableArray alloc] init];
        TableIntervalBean * bean = [[TableIntervalBean alloc] init];
        [beans addObject:bean];
        
        [arrays addObject:beans];
    }
    //智能分析
    {
        beans = nil;
        beans = [NSMutableArray array];
        ResultInfoTitleBean *titleBean = [[ResultInfoTitleBean alloc] init];
        titleBean.titleImageName = @"ecg_img_fenxibaogao";
        titleBean.title = INTERNATIONAL(@"string_intelligent_analys");
        [beans addObject:titleBean];
        ResultTextBean *textBean = [[ResultTextBean alloc] init];
        textBean.text = [self getSuggestStr:ecgsymps];
        [beans addObject:textBean];
        [arrays addObject:beans];
    }
    self.cellBeans = arrays;
    [self.tableView reloadData];
}

#pragma mark -UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.cellBeans.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.cellBeans objectAtIndex:section].count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    CellBean* bean = [[self.cellBeans objectAtIndex:section] objectAtIndex:row];
    return bean.cellHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    CellBean* cellBean = [[self.cellBeans objectAtIndex:section] objectAtIndex:row];
    switch (cellBean.cellType) {
        case CellTypeTitle:
        {
            ResultInfoTitleBean *  bean= (ResultInfoTitleBean*)cellBean;
            ResultInfoTitleCell *cell = [ResultInfoTitleCell createWith:tableView bean:bean];
            return cell;
            
        }
        case CellTypeContent:
        {
            ResultContentBean *bean = (ResultContentBean*)cellBean;
            ResultContentCell *cell = [ResultContentCell createWith:tableView bean:bean];
            return cell;
            
        }
        case CellTypeProgress:
        {
            ResultProgressBean *bean = (ResultProgressBean*)cellBean;
            ResultProgressCell *cell = [ResultProgressCell createWith:tableView bean:bean];
            return cell;
        }
        case CellTypeText:
        {
            ResultTextBean *bean = (ResultTextBean*)cellBean;
            ResultTextCell *cell = [ResultTextCell createWith:tableView bean:bean];
            return cell;
            
        }
            
        case CellTypeInterval:
        {
            TableIntervalBean *bean = (TableIntervalBean*)cellBean;
            TableIntervalCell *cell = [TableIntervalCell createWith:tableView bean:bean];
            return cell;
        }
        case CellTypeHeartRateProgress:
        {
            HeartRateProgressBean *bean = (HeartRateProgressBean*)cellBean;
            HeartRateProgressCell *cell = [HeartRateProgressCell createWith:tableView bean:bean];
            return cell;
        }
        case CellTypeBreatheRateProgress:
        {
            BreatheRateProgressBean *bean = (BreatheRateProgressBean*)cellBean;
            BreatheRateProgressCell *cell = [BreatheRateProgressCell createWith:tableView bean:bean];
            return cell;
        }
        case CellTypeResult:
        {
            ResultBean *bean = (ResultBean*)cellBean;
            ResultCell *cell = [ResultCell createWith:tableView bean:bean];
            return cell;
        }
        default:
        {
            return nil;
        }
    }
}

#pragma mark --屏幕旋转
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation) ) { // 横屏
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];

        [self.reportChartView removeFromSuperview];
        [self.lineChartRootView addSubview:self.reportChartView];
        self.lineChartRootView.backgroundColor = [UIColor blackColor];
        self.lineChartRootView.hidden = NO;
        [self.reportChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.lineChartRootView);
            make.height.equalTo(@(ecgViewHeight));
            make.left.right.equalTo(self.lineChartRootView);
        }];
        [self.reportChartView rotateEcgChartView:false];
    } else { // 竖屏
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self.reportChartView removeFromSuperview];
        [self.reportChartView rotateEcgChartView:true];
        self.lineChartRootView.hidden = YES;
        self.lineChartRootView.backgroundColor = [UIColor clearColor];
        [self.tableView.tableHeaderView addSubview:self.reportChartView];
        [self.reportChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.tableView.tableHeaderView);
        }];
        [self.tableView reloadData];
    }
}


- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return true;
}
@end
